/**
 * Created by Administrator on 2016/10/9.
 */
import { notification, Modal, message } from 'antd';
import {browserHistory} from 'react-router';
import * as axios from 'axios';
axios.defaults.baseURL = window.GLOBAL.baseURL;
axios.defaults.headers.post['Content-Type'] = window.GLOBAL.contentType;

//首页轮播图
export function findCarousels(obj) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/home/unAuth/findCarousels', null)
    .then(function (response) {
        if(response.data.code == 1){
          // debugger;
          obj.setState({
            carouselData: ((response.data.data.false == undefined)?[]:response.data.data.false),
            typeData: ((response.data.data.true == undefined)?[]:response.data.data.true)
          });
        }
    }).catch(function(err){
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: "对不起，网络请求错误。",
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//首页查找商品列表
export function findExtensionProducts(obj, paramData) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }

    axios.post('/webAPI/home/unAuth/findExtensionProducts', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if (paramData.conditions.setTopType != undefined) {
            obj.setState({
              productList: response.data.data.content
            });
          }else if (paramData.conditions.mustCheckOut != undefined) {
            obj.setState({
              mustCheckOutList: response.data.data.content
            });
          }
        }
    }).catch(function(err){
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: "对不起，网络请求错误。",
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//查找商品详情
export function findProductDetial(obj, pId) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/home/unAuth/findProductDetial/' + pId, null)
    .then(function (response) {
        if(response.data.code == 1){
          obj.setState({
            productDetial: response.data.data,
            selectColors: response.data.data.product.productColors[0],
            selectSizes: response.data.data.product.sizes[0]
          });
          if(sessionStorage.getItem("username") != null){
            findProfileById(obj, response.data.data.product.id);
          }
        }
    }).catch(function(err){
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: "对不起，网络请求错误。",
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
    })
}
//添加修改购物车
export function addOrEditShoppingCart(obj, paramData, flag) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/shoppingCart/addOrEditShoppingCart', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if(flag == "add"){
            $(".imgShoppingAnimation").css("margin-left", "327px");
            $(".imgShoppingAnimation").css("margin-top", "-131px");
            $(".imgShoppingAnimation").css("opacity", "1");
            setTimeout(function(){
              $(".imgShoppingAnimation").css("margin-left", (document.body.clientWidth/2) + 130 + "px");
              $(".imgShoppingAnimation").css("margin-top", "-95px");
              $(".imgShoppingAnimation").css("opacity", "0");
              setTimeout(function(){
                $(".imgShoppingAnimation").css("margin-left", "235px");
                $(".imgShoppingAnimation").css("margin-top", "-54px");
                obj.refs["sidebar"].findShoppingCartList();
                Modal.success({
                  title: '提示：',
                  content: '购物车 添加成功！'
                });
              }, 400);
            }, 400);
          }else {
            Modal.success({
              title: '提示：',
              content: '购物车 编辑成功！'
            });
          }
        }
    }).catch(function(err){
      if(err.response.status == 401){
        Modal.warning({
          title: '提示：',
          content: '请登录，查看购物车。'
        });
      }else {
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: "对不起，网络请求错误。",
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
      }
    })
}
//添加修改购物车
export function addOrEditShoppingCartByEdit(obj, paramData, flag) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/shoppingCart/addOrEditShoppingCart', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if(flag == "num"){
            obj.findShoppingCartList();
          }else {
            obj.setState({updateLoading: false, colorSizes: false});
            Modal.success({
              title: '提示：',
              content: '购物车 编辑成功！',
              onOk: ()=>{
                obj.findShoppingCartList();
              }
            });
          }
        }
    }).catch(function(err){
      if(err.response.status == 401){
        Modal.warning({
          title: '提示：',
          content: '请登录，查看购物车。'
        });
      }else {
        notification.error({
            placement: 'bottomRight',
            message: '提示：',
            description: "对不起，网络请求错误。",
            style: {
              borderLeft: '4px solid rgb(240, 70, 52)'
            }
        });
      }
    })
}
//删除购物车 List<String> scIds
export function removeShoppingCart(obj, scIds) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/shoppingCart/removeShoppingCart', scIds)
    .then(function (response) {
        if(response.data.code == 1){
          obj.findShoppingCartList();
          Modal.success({
            title: '提示：',
            content: '购物车 删除成功！'
          });
        }
    }).catch(function(err){
        if(err.response.status == 401){
          Modal.warning({
            title: '提示：',
            content: '请登录，查看购物车。'
          });
        }else {
          notification.error({
              placement: 'bottomRight',
              message: '提示：',
              description: "对不起，网络请求错误。",
              style: {
                borderLeft: '4px solid rgb(240, 70, 52)'
              }
          });
        }
    })
}
//获取购物车列表
export function findShoppingCartList(obj, paramData) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    obj.setState({loading: true, cartIsEmpty: false});
    axios.post('/webAPI/shoppingCart/findShoppingCartList', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if(response.data.data.total <= 0){
            obj.setState({
              shoppingCartList: [],
              totalAmount: 0,
              totalNum: 0,
              loading: false,
              cartIsEmpty: true
            });
          }else {
            var totalAmount = 0; var totalNum = 0;
            for (var i = 0; i < response.data.data.content.length; i++) {
              totalAmount += response.data.data.content[i].discountPrice * response.data.data.content[i].purchaseNum;
              totalNum += response.data.data.content[i].purchaseNum;
            }
            totalAmount = totalAmount.toFixed(2);
            obj.setState({
              shoppingCartList: response.data.data.content,
              totalAmount: totalAmount,
              totalNum: totalNum,
              loading: false,
              cartIsEmpty: false
            });
          }
        }
    }).catch(function(err){
        obj.setState({loading: false, cartIsEmpty: false});
        if(err.response.status == 401){
          Modal.warning({
            title: '提示：',
            content: '请登录，查看购物车。'
          });
        }else {
          Modal.error({
            title: '提示：',
            content: '对不起，网络请求错误。'
          });
        }
    })
}
//获取购物车列表
export function findShoppingCartListByType(obj, paramData) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    obj.setState({loading: true, cartIsEmpty: false});
    axios.post('/webAPI/shoppingCart/findShoppingCartList', paramData)
    .then(function (response) {
        if(response.data.code == 1){
          if(response.data.data.total <= 0){
            obj.setState({
              shoppingCartList: [],
              loading: false,
              cartIsEmpty: true
            });
          }else {


            var tempArray = [];
            for (var i = 0; i < response.data.data.content.length; i++) {
              var content = response.data.data.content[i];

              if(tempArray.length <= 0){
                var tempObj = {};
                tempObj.type = content.type;
                tempObj.typeIndeterminate = false;
                tempObj.isCheck = false;
                switch (content.type) {
                  case "1":
                    tempObj.typeText = "推荐品牌";
                    break;
                  case "2":
                    tempObj.typeText = "女孩护肤";
                    break;
                  case "3":
                    tempObj.typeText = "面膜";
                    break;
                  case "4":
                    tempObj.typeText = "彩妆/口红";
                    break;
                  case "5":
                    tempObj.typeText = "个人护理";
                    break;
                  case "6":
                    tempObj.typeText = "保健产品";
                    break;
                }
                content.isCheck = false;
                tempObj.items = new Array(content);
                tempArray.push(tempObj);
              }else {
                var objItem = null;
                for (var j = 0; j < tempArray.length; j++) {
                  if (tempArray[j].type == content.type){
                    objItem = tempArray[j]; break;
                  }
                }
                if(objItem == null){
                  var tempObj = {};
                  tempObj.type = content.type;
                  tempObj.typeIndeterminate = false;
                  tempObj.isCheck = false;
                  switch (content.type) {
                    case "1":
                      tempObj.typeText = "推荐品牌";
                      break;
                    case "2":
                      tempObj.typeText = "女孩护肤";
                      break;
                    case "3":
                      tempObj.typeText = "面膜";
                      break;
                    case "4":
                      tempObj.typeText = "彩妆/口红";
                      break;
                    case "5":
                      tempObj.typeText = "个人护理";
                      break;
                    case "6":
                      tempObj.typeText = "保健产品";
                      break;
                  }
                  content.isCheck = false;
                  tempObj.items = new Array(content);
                  tempArray.push(tempObj);
                }else {
                  objItem.items.push(content);
                }
              }
            }

            for (var i = 0; i < obj.state.shoppingCartList.length; i++) {
              for (var j = 0; j < tempArray.length; j++) {
                if(obj.state.shoppingCartList[i].type == tempArray[j].type){
                  tempArray[j].typeIndeterminate = obj.state.shoppingCartList[i].typeIndeterminate;
                  tempArray[j].isCheck = obj.state.shoppingCartList[i].isCheck;

                  for (var x = 0; x < tempArray[j].items.length; x++) {
                    for (var y = 0; y < obj.state.shoppingCartList[i].items.length; y++) {
                      if(tempArray[j].items[x].id == obj.state.shoppingCartList[i].items[y].id){
                        tempArray[j].items[x].isCheck = obj.state.shoppingCartList[i].items[y].isCheck
                      }
                    }
                  }
                }
              }
            }
            obj.setState({
              rawData: response.data.data.content,
              shoppingCartList: tempArray,
              loading: false,
              cartIsEmpty: false
            });
          }
        }
    }).catch(function(err){
        obj.setState({loading: false, cartIsEmpty: false});
        if(err.response != undefined && err.response.status == 401){
          Modal.warning({
            title: '提示：',
            content: '请登录，查看购物车。'
          });
        }else {
          Modal.error({
            title: '提示：',
            content: '对不起，网络请求错误。'
          });
        }
    })
}
//添加评论
export function addComment(obj, pId, paramData) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/product/comment/' + pId, paramData)
    .then(function (response) {
        if(response.data.code == 1){
          obj.setState({
            isAnonymity: false,
            textContent: ""
          }, function(){
            findProductDetial(obj, obj.props.routeParams.id);
          });
          notification.success({
              placement: 'bottomRight',
              message: '提示：',
              description: '评论已经发布成功。',
              style: {
                borderLeft: '4px solid rgb(23, 168, 84)'
              }
          });
        }
    }).catch(function(err){
        Modal.error({
          title: '提示：',
          content: '对不起，网络请求错误。'
        });
    })
}
//查询个人信息，以便知道是否收藏
export function findProfileById(obj, pId) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/setting/findProfileById')
    .then(function (response) {
        if(response.data.code != 0){
          if(response.data.data.followProductIds.length <= 0){
            obj.setState({isFollow: false, isDisable: false});
          }else {
            var havepId = false;
            for (var i = 0; i < response.data.data.followProductIds.length; i++) {
              var id = response.data.data.followProductIds[i];
              if(id == pId){
                havepId = true;
              }
            }
            obj.setState({isFollow: havepId, isDisable: false});
          }
        }
    })
}
//收藏商品列表
export function findFollowProducts(obj) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/setting/findFollowProducts', null)
    .then(function (response) {
        if(response.data.code == 1){
          obj.setState({serviceData: response.data.data});
        }
    }).catch(function(err){
        if(err.response != undefined && err.response.status == 401){
          Modal.warning({
            title: '提示：',
            content: '请登录，才能收藏商品。'
          });
        }else {
          Modal.error({
            title: '提示：',
            content: '对不起，网络请求错误。'
          });
        }
    })
}
//收藏商品
export function weatherFollow(obj, pId, weatherFollow, flag) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/shoppingCart/weatherFollow/' + pId + '/' + weatherFollow, null)
    .then(function (response) {
        if(response.data.code == 1){
          if(weatherFollow == "follow"){
            notification.success({
                placement: 'bottomRight',
                message: '提示：',
                description: '商品关注（+1）。',
                style: {
                  borderLeft: '4px solid rgb(23, 168, 84)'
                }
            });
          }else if(weatherFollow == "unFollow"){
            notification.success({
                placement: 'bottomRight',
                message: '提示：',
                description: '取消 商品关注。',
                style: {
                  borderLeft: '4px solid rgb(23, 168, 84)'
                }
            });
          }
          if(flag == undefined){
            findProfileById(obj, obj.state.productDetial.product.id);
          }else {
            findFollowProducts(obj);
          }
        }
    }).catch(function(err){
        if(err.response != undefined && err.response.status == 401){
          Modal.warning({
            title: '提示：',
            content: '请登录，才能收藏商品。'
          });
        }else {
          Modal.error({
            title: '提示：',
            content: '对不起，网络请求错误。'
          });
        }
    })
}
//添加意见反馈
export function addFeedback(obj, content) {
    if(sessionStorage.getItem("userAuth") != null){
        axios.defaults.headers.common['userAuth'] = sessionStorage.getItem('userAuth');
    }
    axios.post('/webAPI/feedback/addFeedback', content)
    .then(function (response) {
        if(response.data.code == 1){
          obj.setState({ showFeedback: false });
          Modal.success({
            title: '提示：',
            content: '意见反馈成功。'
          });
        }
    }).catch(function(err){
        if(err.response != undefined && err.response.status == 401){
          Modal.warning({
            title: '提示：',
            content: '请登录，才能意见反馈。'
          });
        }else {
          Modal.error({
            title: '提示：',
            content: '对不起，网络请求错误。'
          });
        }
    })
}
